package com.xmut.bs.handaccount.activity;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ImageView;

import com.sendtion.xrichtext.RichTextEditor;
import com.xmut.bs.handaccount.GlideApp;
import com.xmut.bs.handaccount.R;
import com.xmut.bs.handaccount.base.ToolbarBaseActivity;
import com.xmut.bs.handaccount.bean.ArtContentType;
import com.xmut.bs.handaccount.bean.VideoBean;
import com.xmut.bs.handaccount.bmob.Article;
import com.xmut.bs.handaccount.bmob.User;
import com.xmut.bs.handaccount.util.CommonUtil;
import com.xmut.bs.handaccount.util.ImageUtils;
import com.xmut.bs.handaccount.util.SDCardUtil;
import com.xmut.bs.handaccount.util.StringUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadBatchListener;
import me.iwf.photopicker.PhotoPicker;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.xmut.bs.handaccount.base.Constants.VERIFY_SUCCESS;
import static com.xmut.bs.handaccount.base.Constants.VERIFY_WAIT;

/**
 * Author Dollkey
 * Date 2018/4/10 16:43.
 */

public class AddArticleActivity extends ToolbarBaseActivity implements RichTextEditor.OnDeleteImageListener {

    @BindView(R.id.add_pic)
    ImageView mAddPic;
    @BindView(R.id.title)
    EditText mTitle;
    @BindView(R.id.et_new_content)
    RichTextEditor mEtNewContent;

    private ProgressDialog insertDialog;
    private ProgressDialog saveDialog;
    private Subscription subsInsert;
    private Subscription subsSave;
    private String coverImg;
    private boolean hasVideo;

    @Override
    protected String getSubTitle() {
        return "添加文章";
    }

    @Override
    protected int bindLayoutId() {
        return R.layout.activity_add_article;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        insertDialog = new ProgressDialog(this);
        insertDialog.setMessage("正在插入图片...");
        insertDialog.setCanceledOnTouchOutside(false);
        saveDialog = new ProgressDialog(this);
        saveDialog.setMessage("正在保存文章...");
        saveDialog.setCanceledOnTouchOutside(false);

    }

    @Override
    protected void initParams(Intent intent) {

    }

    @OnClick(R.id.add_pic)
    public void onViewClicked() {
        callGallery(999);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_new, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_insert_image:
                callGallery(1);
                //                callGallery(PhotoPicker.REQUEST_CODE);
                break;
            case R.id.action_insert_video:
                if (hasVideo) {
                    showToast("只能添加一段视频");
                } else {
                    choiceVideo();
                }
                break;
            case R.id.action_new_save:
                saveNoteData();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private List<String> filePaths;

    private void saveNoteData() {
        if (BmobUser.getCurrentUser(User.class) == null) {
            showToast("请先登录");
            return;
        }
        saveDialog.show();
        filePaths = new ArrayList<>();
        filePaths.add(coverImg);
        final List<ArtContentType> datas = getEditData();
        BmobFile.uploadBatch(filePaths.toArray(new String[filePaths.size()]), new UploadBatchListener() {
            @Override
            public void onSuccess(List<BmobFile> files, List<String> urls) {
                //1、files-上传完成后的BmobFile集合，是为了方便大家对其上传后的数据进行操作，例如你可以将该文件保存到表中
                //2、urls-上传文件的完整url地址
                int size = urls.size();
                if (size == filePaths.size()) {//如果数量相等，则代表文件全部上传完成
                    Article article = new Article();
                    article.setUser(BmobUser.getCurrentUser(User.class));
                    int j = 1;
                    for (ArtContentType data : datas) {
                        if (data.getType() == 2) {
                            data.setContent(urls.get(j++));
                        } else if (data.getType() == 3) {
                            String content = urls.get(j++);
                            data.setContent(content);
                            VideoBean bean = data.getVideoBean();
                            bean.setImagePath(content);
                            bean.setVideoPath(urls.get(j++));
                            data.setVideoBean(bean);
                        }
                    }
                    article.setContents(datas);
                    article.setCoverImg(urls.get(0));
                    article.setStatus(hasVideo ? VERIFY_WAIT : VERIFY_SUCCESS);
                    article.setContainVideo(hasVideo);
                    article.setTitle(mTitle.getText().toString().trim());
                    article.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            saveDialog.dismiss();
                            if (e == null) {
                                showToast("文章保存成功:");
                                finish();
                            } else {
                                showToast("文章保存失败:" + e.getMessage());
                            }
                        }
                    });
                }
            }

            @Override
            public void onError(int statuscode, String errormsg) {
                saveDialog.dismiss();
                showToast("文章保存失败:" + errormsg);
            }

            //1、curIndex--表示当前第几个文件正在上传
            //2、curPercent--表示当前上传文件的进度值（百分比）
            //3、total--表示总的上传文件数
            //4、totalPercent--表示总的上传进度（百分比）
            @Override
            public void onProgress(int curIndex, int curPercent, int total, int totalPercent) {
            }
        });
    }

    /**
     * 负责处理编辑数据提交等事宜，请自行实现
     */
    private List<ArtContentType> getEditData() {
        List<RichTextEditor.EditData> editList = mEtNewContent.buildEditData();
        List<ArtContentType> list = new ArrayList<>();
        int i = 0;
        for (RichTextEditor.EditData itemData : editList) {
            if (!StringUtil.isNull(itemData.inputStr)) {
                list.add(new ArtContentType(i++, itemData.inputStr, 1));
            } else if (itemData.videoBean != null) {
                filePaths.add(itemData.imagePath);
                filePaths.add(itemData.videoBean.getVideoPath());
                list.add(new ArtContentType(i++, itemData.imagePath, itemData.videoBean, 3));
            } else if (!StringUtil.isNull(itemData.imagePath)) {
                filePaths.add(itemData.imagePath);
                list.add(new ArtContentType(i++, itemData.imagePath, 2));
            }
        }
        return list;
    }

    /**
     * 从相册中选择视频
     */
    private void choiceVideo() {
        Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, 66);
    }

    /**
     * 调用图库选择
     */
    private void callGallery(int code) {
        //调用系统图库
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");// 相片类型
        startActivityForResult(intent, code);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                if (requestCode == 1) {
                    //处理调用系统图库
                    insertImagesSync(data, null);
                } else if (requestCode == 999) {
                    Uri uri = data.getData();
                    String[] proj = {MediaStore.Images.Media.DATA};
                    Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
                    int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    actualimagecursor.moveToFirst();
                    int width = CommonUtil.getScreenWidth(mContext);
                    int height = CommonUtil.getScreenHeight(mContext);
                    Bitmap bitmap = ImageUtils.getSmallBitmap(actualimagecursor.getString(actual_image_column_index), width, height);//压缩图片
                    coverImg = SDCardUtil.saveToSdCard(bitmap);
                    GlideApp.with(mAddPic).load(data.getData()).fitCenter().into(mAddPic);
                } else if (requestCode == 66) {
                    //处理调用系统视频
                    //                    videoProgress(data);
                    insertImagesSync(data, new VideoBean());
                } else if (requestCode == PhotoPicker.REQUEST_CODE) {
                    //异步方式插入图片
                    insertImagesSync(data, null);
                }
            }
        }
    }

    /**
     * 异步方式插入图片
     *
     * @param data
     */
    private void insertImagesSync(final Intent data, final VideoBean videoBean) {
        insertDialog.show();
        subsInsert = Observable
                .create(new Observable.OnSubscribe<String>() {
                    @Override
                    public void call(Subscriber<? super String> subscriber) {
                        try {
                            mEtNewContent.measure(0, 0);
                            int width = CommonUtil.getScreenWidth(mContext);
                            int height = CommonUtil.getScreenHeight(mContext);

                            Uri uri = data.getData();
                            Bitmap bitmap;
                            //                            String[] proj = {MediaStore.Images.Media.DATA};
                            ContentResolver cr = mContext.getContentResolver();
                            Cursor cursor = cr.query(uri, null, null, null, null);
                            //                            int actual_image_column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                            cursor.moveToFirst();
                            String img_path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
                            if (videoBean != null) {
                                // 视频路径：MediaStore.Audio.Media.DATA
                                String videoPath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
                                // 视频时长：MediaStore.Audio.Media.DURATION
                                int duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION));
                                // 视频大小：MediaStore.Audio.Media.SIZE
                                long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
                                videoBean.setDuration(duration);
                                videoBean.setSize(size);
                                videoBean.setVideoPath(videoPath);
                                videoBean.setImagePath(img_path);
                                bitmap = ThumbnailUtils.createVideoThumbnail(img_path, MediaStore.Video.Thumbnails.MICRO_KIND);
                            } else {
                                bitmap = ImageUtils.getSmallBitmap(img_path, width, height);//压缩图片
                            }
                            cursor.close();
                            subscriber.onNext(SDCardUtil.saveToSdCard(bitmap));
                            subscriber.onCompleted();
                        } catch (Exception e) {
                            e.printStackTrace();
                            subscriber.onError(e);
                        }
                    }
                })
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())//生产事件在io
                .observeOn(AndroidSchedulers.mainThread())//消费事件在UI线程
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        insertDialog.dismiss();
                        mEtNewContent.addEditTextAtIndex(mEtNewContent.getLastIndex(), " ");
                        hasVideo = videoBean != null;
                        showToast(hasVideo ? "视频添加成功" : "图片插入成功");
                    }

                    @Override
                    public void onError(Throwable e) {
                        insertDialog.dismiss();
                        showToast((videoBean == null ? "图片插入失败" : "视频添加失败") + e.getMessage());
                    }

                    @Override
                    public void onNext(String imagePath) {
                        mEtNewContent.insertImage(imagePath, mEtNewContent.getMeasuredWidth(), videoBean);
                    }
                });
    }

    @Override
    public void onDeleteImage(String imagePath, VideoBean videoBean) {
        if (videoBean != null)
            hasVideo = false;
    }
}
